package yt.kpool.activity.setting.agent.returnpointquery;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yt.kpool.R;

import yt.kpool.activity.setting.AccountListActivity;
import yt.kpool.activity.setting.EditAccountActivity;
import yt.kpool.adapter.AccountListviewAdapter;
import yt.kpool.adapter.MinerListAdapter;
import yt.kpool.adapter.ReturnPointAdapter;
import yt.kpool.bean.ChildAccountBean;
import yt.kpool.bean.CurrencyList;
import yt.kpool.bean.MinerBean;
import yt.kpool.bean.ReturnPointBean;
import yt.kpool.network.HttpUtils;
import yt.kpool.network.MyGson;
import yt.kpool.network.NetHelperNew;
import yt.kpool.util.NetWorkUtil;

import yt.kpool.util.ToastUtil;
import yt.kpool.util.imageUtil.GlideUtil;
import yt.kpool.view.dialog.ErrorDialog;
import yt.kpool.view.dialog.LoadingDialog;
import yt.kpool.view.dialog.StopPayDialog;
import yt.kpool.view.pop.CurrencyPopupWindow;

/**
 * 返点查询
 */
public class ReturnPointQueryActivity extends AppCompatActivity {

    @BindView(R.id.recyleview)
    LRecyclerView mRecyclerView;

    @BindView(R.id.tv_starttime)
    TextView tv_starttime;//开始时间
    @BindView(R.id.tv_endtime)
    TextView tv_endtime;//结束时间
    @BindView(R.id.tv_totalAmount)
    TextView tv_totalAmount;
    @BindView(R.id.tv_Balance)
    TextView tv_Balance;
    @BindView(R.id.tv_currrncyname)
    TextView tv_currrncyname;
    @BindView(R.id.iv_curreney)
    ImageView iv_curreney;
    @BindView(R.id.ll_currency)
    LinearLayout ll_currency;
    private List<CurrencyList.DataBean> currencyListData;
    private CurrencyPopupWindow currencyPopupWindow;//币种选择
    private LoadingDialog loadingDialog;
    private int currencyId;//币种id
    private String currencycode = "";//币种code


    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private List<ReturnPointBean.DataBean.ProportionRunningsBean> dataBeanList;
    private ReturnPointAdapter returnPointAdapter;//返点列表

    private SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
    private int startOrEnd = 0;//1 开始时间 2 结束时间
    private TimePickerView pvTimeDay;//年月日时间选择器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_point_query);
        ButterKnife.bind(this);
        initPvTimeYear();
        init();

        initList();

    }

    /**
     * 列表初始化
     */
    private void initList() {
        dataBeanList = new ArrayList<>();
        returnPointAdapter = new ReturnPointAdapter(this, dataBeanList);

        lRecyclerViewAdapter = new LRecyclerViewAdapter(returnPointAdapter);
        //空白页
        mRecyclerView.setEmptyView(findViewById(R.id.empty));
        findViewById(R.id.tv_refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refreshClear();

            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(lRecyclerViewAdapter);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader); //设置下拉刷新Progress的样式
        // mRecyclerView.setArrowImageView(R.drawable.iconfont_downgrey);  //设置下拉刷新箭头
        //设置头部加载颜色
        mRecyclerView.setHeaderViewColor(R.color.system_color, R.color.system_color, R.color.white);
//设置底部加载颜色
        mRecyclerView.setFooterViewColor(R.color.system_color, R.color.system_color, android.R.color.white);

        //分割线
        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.d_1)
                .setPadding(R.dimen.d_0)
                .setColorResource(R.color.colorLine)
                .build();
        mRecyclerView.addItemDecoration(divider);
        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {//下拉刷新
            @Override
            public void onRefresh() {

                refreshClear();
            }
        });
        //停止下拉刷新
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadMoreEnabled(false);
        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {//加载更多
            @Override
            public void onLoadMore() {
//                getData(pagenum, false);
            }
        });
    }

    /**
     * 刷新数据
     */
    private void refreshClear() {
        dataBeanList.clear();
        returnPointAdapter.notifyDataSetChanged();
        getdata();
    }

    private void init() {

        loadingDialog = new LoadingDialog(this, 0);
        if (NetWorkUtil.checkNet(ReturnPointQueryActivity.this)) {
            getCurrrencyData();
        } else {

            ToastUtil.showToast(ReturnPointQueryActivity.this, getResources().getString(R.string.internet_error));
        }
    }

    /**
     * 点击事件的处理
     *
     * @param view
     */
    @OnClick({R.id.ll_starttime, R.id.ll_endtime, R.id.ll_currency, R.id.ll_finish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_starttime:
                //开始时间
                startOrEnd = 1;
                //设置选择时间
                pvTimeDay.setTime(getFormatDate(tv_starttime.getText().toString()));
                pvTimeDay.show();
                break;
            case R.id.ll_endtime:
                //结束时间
                startOrEnd = 2;
                //设置选择时间
                pvTimeDay.setTime(getFormatDate(tv_endtime.getText().toString()));
                pvTimeDay.show();
                break;

            case R.id.ll_finish:

                finish();
                break;
            case R.id.ll_currency:
                //选择币种
                if (currencyPopupWindow != null)
                    currencyPopupWindow.showAsDropDown(ll_currency, 0, 0);
                break;


        }
    }


    /**
     * 转化时间
     *
     * @param s
     * @return
     */
    private Date getFormatDate(String s) {
        try {
            return ymd.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 年月日时间选择器
     */
    private void initPvTimeYear() {

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1); //向前走一天
        Date date = calendar.getTime();
        tv_starttime.setText(ymd.format(date));
        tv_endtime.setText(ymd.format(new Date(System.currentTimeMillis())));


        // 时间选择器
        pvTimeDay = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        //设置范围
        pvTimeDay.setRange(2017, 2030);

        //设置是否循环滚动
        pvTimeDay.setCyclic(false);
        pvTimeDay.setCancelable(true);

        //时间选择后回调
        pvTimeDay.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                if (startOrEnd == 1) {
                    tv_starttime.setText(ymd.format(date));
                } else if (startOrEnd == 2) {
                    tv_endtime.setText(ymd.format(date));
                }

                refreshClear();
            }


        });
    }

    /**
     * 获取网络数据
     */
    private void getdata() {

        if (NetWorkUtil.check(this)) {

            loadingDialog.show();
            NetHelperNew.ProportionList(currencyId + "", tv_starttime.getText().toString().trim(), tv_endtime.getText().toString().trim(), new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    loadingDialog.dismiss();
                    Log.i("-->","返点查询"+data);
                    ReturnPointBean returnPointBean = MyGson.getInstance().fromJson(data, ReturnPointBean.class);
                    if (returnPointBean.getType() == 1) {
                        tv_totalAmount.setText(""+returnPointBean.getData().getTotalAmount());
                        tv_Balance.setText(""+returnPointBean.getData().getBalance());
                        mRecyclerView.refreshComplete(10);

                        //更新数据
                        dataBeanList.addAll(returnPointBean.getData().getProportionRunnings());
                        returnPointAdapter.notifyDataSetChanged();


                    } else {
                        mRecyclerView.refreshComplete(10);
                        ToastUtil.showToast(ReturnPointQueryActivity.this, returnPointBean.getContent());

                    }


                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);


                    loadingDialog.dismiss();

                    mRecyclerView.refreshComplete(10);
                    ToastUtil.showToast(ReturnPointQueryActivity.this, msg);
                }
            });
        }
    }

    /**
     * 币种选择pop初始化
     */
    private void initCurrencyPopupWindow() {
        currencyPopupWindow = new CurrencyPopupWindow(currencyListData, this, new CurrencyPopupWindow.OnSeleCurrencyLayoutListener() {
            @Override
            public void selectHouseLayout(int i) {
                currencyId = currencyListData.get(i).getId();
                currencycode = currencyListData.get(i).getCode();
                GlideUtil.loadImage(ReturnPointQueryActivity.this, NetHelperNew.URL + currencyListData.get(i).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                tv_currrncyname.setText(currencyListData.get(i).getCode().toUpperCase());

                refreshClear();

            }
        });
    }

    /**
     * 获取币种数据
     */
    private void getCurrrencyData() {
        currencyListData = new ArrayList<>();
        if (NetWorkUtil.check(this)) {
            loadingDialog.show();

            NetHelperNew.GetCurrencyList(new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {

                    Log.i("-->", "币种列表：" + data);
                    CurrencyList currencyList = MyGson.getInstance().fromJson(data, CurrencyList.class);
                    if (currencyList.getType() == 1) {

                        currencyListData.addAll(currencyList.getData());
                        initCurrencyPopupWindow();
                        if (currencyList.getData().size() > 0) {
                            currencycode = currencyList.getData().get(0).getCode();
                            currencyId = currencyList.getData().get(0).getId();
                            GlideUtil.loadImage(ReturnPointQueryActivity.this, NetHelperNew.URL + currencyListData.get(0).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                            tv_currrncyname.setText(currencyListData.get(0).getCode().toUpperCase());

                        }
                       refreshClear();
                    } else {
                        loadingDialog.dismiss();
                        new ErrorDialog(ReturnPointQueryActivity.this, currencyList.getContent()).show();
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);
                    loadingDialog.dismiss();

                    ToastUtil.showToast(ReturnPointQueryActivity.this, msg);
                }
            });


        }

    }
}
